<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once ('mailer.php');
require_once ('db.php');
$db = getDb();

$content=file_get_contents("../view/info.html");
$_STATUS_="_STATUS_";
$_STATUS_content="OK";

$id = $_POST["id"];
$subject = $_POST["subject"];
$to = $_POST["to"];

$startDate = $_POST["startDate"];
$length = $_POST["length"];

$cc = array();
if(isset($_POST['cc']) && $_POST['cc'])
	$cc =  $_POST['cc'];

$bcc = array();
if(isset($_POST['bcc']) && $_POST['bcc'])
	$bcc =  $_POST['bcc'];

$message = $_POST['message'];

function customize($data,$emailId)
{
	$db = getDb();
	$sqlCommand="SELECT name FROM email WHERE id=".$emailId;
	$result = $db->Execute($sqlCommand);
	
	if ($result === false)
		die($sqlCommand);
	
	$destData = $result->fields[0];
	
	$newData = str_replace("%NAME%", $destData, $data);
	return $newData;
}

function getEmailsId($table)
{
	$emails = array();
	foreach ($table as $element) {
		
		if($element[0] == 'e' )
			{
	    	$emails[] = substr($element,1);
			}
	}

	return $emails;
}

function getEmailsAddress($table)
{
	$emailsNames = array();
	$db = getDb();
	foreach ($table as $element) {

		
		$sqlCommand="SELECT address FROM email WHERE id=".$element;
		$result = $db->Execute($sqlCommand);
		
		if ($result === false)
			die($sqlCommand);
		$emailsNames[] = $result->fields[0];
	}

	return $emailsNames;
}

function getGroupsId($table)
{
	$groups = array();
	foreach ($table as $element) {

		if($element[0] == 'g' )
		{
			$groups[] = substr($element,1);
		}
	}
	return $groups;
}

function getGroupsMailsId($table)
{
	$emailsId=array();
	
	$groupsIds= getGroupsId($table);
	foreach ($groupsIds as $groupId) {
	
		$db = getDb();
		$sqlCommand="SELECT e.id FROM email e JOIN emailgroup eg ON e.id = eg.emailId JOIN groups g ON eg.groupId = g.id WHERE g.id = ". $groupId ."";
		
		$result = $db->Execute($sqlCommand);
		
		if ($result === false)
			die($sqlCommand);
	
		while (!$result->EOF)
		{
			$emailsId[]= $result->fields[0];
			$result->MoveNext();
		}
	}
	return $emailsId;
}

function checkEmail($emailid, $id)
{
	$db = getDb();
	$sqlCommand="SELECT * FROM unsub WHERE emailid=". $emailid . " AND eventid=".$id;
	
	$result = $db->Execute($sqlCommand);
	
	if ($result === false)
		die($sqlCommand);
	
	
	if ($result->EOF)
	{
		return 1;
	}
	else 
	{
		return 0;
	}
	
}

function sendEmail($subeventId,$emailId,$ccWho,$bccWho)
{

	global $subject, $message, $id, $orgFilename, $storageFilename;
	
	// dont send to unsubscribers
	if(checkEmail($emailId,$id) == 0)
		return;
	
	
	$db = getDb();
	$sqlCommand="INSERT INTO sentsingle(subeventid,emailid,type) values(".
			$subeventId . ",". $emailId . ",0) ";
	
	//echo $sqlCommand . "<br>";
	$result = $db->Execute($sqlCommand);
	
	if ($result === false)
		die($sqlCommand);
	
	
	$customMessage = customize($message, $emailId);
	$customMessage .= "\nFeel: http://localhost/Scheduler/controller/schedule.php?eventid=1&emailid=".$emailId."&subeventid=".$subeventId;
	
	//echo $subject . "<br/>";
	//echo $customMessage . "<br/>";
	//echo getEmailsAddress(array($emailId))[0];
	$tmp0 = array($emailId);
	$tmp1 = getEmailsAddress($tmp0);
	$tmp2 = $tmp1[0];
	sendEmailXpm4($tmp2, $ccWho, $bccWho, $subject, $customMessage, $storageFilename, $orgFilename);
	
	
}	

function sendToAll($subeventId,$toWho,$ccWho,$bccWho)
{
	$CCfromGroups=getGroupsMailsId($ccWho) ;
	$BCCfromGroups=getGroupsMailsId($bccWho) ;
	
	$CCfromSingles=getEmailsId($ccWho) ;
	$BCCfromSingles=getEmailsId($bccWho) ;
	

	if(!is_array ( $CCfromGroups ))
		$CCfromGroups= array();
	if(!is_array ( $CCfromSingles ))
		$CCfromSingles= array();
	if(!is_array ( $BCCfromGroups ))
		$BCCfromGroups= array();
	if(!is_array ( $BCCfromSingles ))
		$BCCfromSingles= array();
	
	$emailsCCids = array_merge($CCfromGroups,$CCfromSingles);
	$emailsBCCids = array_merge($BCCfromGroups,$BCCfromSingles);
	
	$emailsCC = getEmailsAddress( $emailsCCids );
	$emailsBCC = getEmailsAddress( $emailsBCCids );
	
	//print_r($emailsCC);
	//print_r($emailsBCC);
	
	$db = getDb();
	// save CC
	foreach ($emailsCCids as $emailId) {
		
		$sqlCommand="INSERT INTO sentsingle(subeventid,emailid,type) values(".
				$subeventId . ",". $emailId . ",1) ";
		
		$result = $db->Execute($sqlCommand);
		if ($result === false)
			die($sqlCommand);	
	}
	// save BCC
	foreach ($emailsBCCids as $emailId) {
	
		$sqlCommand="INSERT INTO sentsingle(subeventid,emailid,type) values(".
				$subeventId . ",". $emailId . ",2) ";
	
		$result = $db->Execute($sqlCommand);
		if ($result === false)
			die($sqlCommand);
	}
	
	foreach (getEmailsId($toWho) as $emailId) {
		sendEmail($subeventId, $emailId,$emailsCC,$emailsBCC);
	}
	foreach (getGroupsMailsId($toWho) as $emailId) {
		sendEmail($subeventId, $emailId,$emailsCC,$emailsBCC);
	}
	
}

	
// message
$sqlCommand="INSERT INTO subevent(eventid,subject,message,startDate,length) values('".
		$id . "','". $subject . "','". $message. "','". $startDate. "','". $length ."') ";
$result = $db->Execute($sqlCommand);

if ($result === false)
	die($sqlCommand);
// getsubeventId

$sqlCommand="SELECT MAX(id) FROM subevent";
$result = $db->Execute($sqlCommand);

if ($result === false)
	die($sqlCommand);

$subeventid = $result->fields[0];

// handle attachements
$storageFilename = "../files" . '/' .microtime(true) . ".txt";
$tempFilename = $_FILES["file"]["tmp_name"];
$orgFilename = $_FILES["file"]["name"];
move_uploaded_file($tempFilename, $storageFilename);


$sqlCommand="INSERT INTO attachment(subeventid,path,orgFilename) values('".
		$subeventid . "','". $storageFilename . "','". $orgFilename ."') ";
$result = $db->Execute($sqlCommand);

if ($result === false)
	die($sqlCommand);

// sending :

sendToAll($subeventid,$to,$cc,$bcc);

	
$content = str_replace($_STATUS_ , $_STATUS_content, $content);
 // Display page
 echo $content;
 
?>
